Page({
    data: {
        categories: [],      // 回收品类
        timeSlots: [],       // 可预约时间段
        address: {},         // 用户地址
        formData: {          // 表单数据
            categoryId: '',
            timeSlotId: '',
            remark: ''
        },
        showCategory: false, // 品类选择器显示状态
        showTime: false,      // 时间选择器显示状态
        activeTimeSlot: null,

        showDate: false,  // 新增日期选择器显示状态
        selectedDate: '',  // 新增选择的日期
        minDate: new Date().getTime(),
        maxDate: new Date(new Date().setMonth(new Date().getMonth() + 1)).getTime(),
        currentDate: new Date().getTime(),

        remark:'',
    },

    onLoad() {
        this.loadInitData();
    },

    // 加载初始数据
    loadInitData() {
        wx.showLoading({ title: '加载中...' });

        // 获取品类数据
        this.getCategories();

        // 获取用户默认地址
        this.getUserAddress();

        wx.hideLoading();
    },

    // 获取回收品类
    getCategories() {
        const mockCategories = [
            { id: 1, name: '废纸类', icon: '' },
            { id: 2, name: '塑料类', icon: '' },
            { id: 3, name: '金属类', icon: '' },
            { id: 4, name: '家电类', icon: '' }
        ];
        this.setData({ categories: mockCategories });
    },

    // 获取用户地址
    getUserAddress() {
        const mockAddress = {
            id: 1,
            address: '北京市朝阳区建国路88号',
            contact: '张先生',
            phone: '13800138000'
        };
        this.setData({ address: mockAddress });
    },

    // 显示品类选择器
    showCategoryPicker() {
        this.setData({ showCategory: true });
    },

    // 确认选择品类
    onCategoryConfirm(e) {
        const category = e.detail.value;
        this.setData({
            'formData.categoryId': category.id,
            'formData.categoryName': category.name,
            showCategory: false
        });
        this.loadTimeSlots();
    },

    // 取消选择品类
    onCategoryCancel() {
        this.setData({ showCategory: false });
    },

    // 加载可预约时间段
    loadTimeSlots(date) {
        // 根据日期获取时间段
        const mockTimeSlots = [
            { id: 1, time_range: '09:00-11:00', available: true },
            { id: 2, time_range: '13:00-15:00', available: true },
            { id: 3, time_range: '15:00-17:00', available: true }
        ];
        this.setData({ timeSlots: mockTimeSlots });
    },

    formatter(type, value) {
        if (type === 'year') {
            return `${value}年`;
        }
        if (type === 'month') {
            return `${value}月`;
        }
        if (type === 'day') {
            return `${value}日`;
        }
        return value;
    },

    showDatePicker() {
        this.setData({ showDate: true });
    },

    // 选择时间段
    selectTimeSlot(e) {
        const id = e.currentTarget.dataset.id;
        this.setData({ activeTimeSlot: id });
    },
    // 确认选择时间
    onTimeConfirm(e) {
        const timeSlot = e.detail.value;
        // 只取时间段部分，去掉日期
        const timeRange = timeSlot.time_range.split(' ')[1] || timeSlot.time_range;
        this.setData({
            'formData.timeSlotId': timeSlot.id,
            'formData.timeSlot': timeRange,
            showTime: false
        });
    },

    onDateConfirm(e) {
        const date = new Date(e.detail);
        const formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        this.setData({
            selectedDate: formattedDate,
            showDate: false
        });
    },

    // 显示时间选择器
    showTimePicker() {
        if (!this.data.formData.categoryId) {
            wx.showToast({ title: '请先选择回收品类', icon: 'none' });
            return;
        }
        if (!this.data.selectedDate) {
            wx.showToast({ title: '请先选择预约日期', icon: 'none' });
            return;
        }
        this.setData({ showTime: true });
    },

    onDateCancel() {
        this.setData({ showDate: false });
    },

    // 取消选择时间
    onTimeCancel() {
        this.setData({ showTime: false });
    },

    // 输入备注变化
    onRemarkChange(e) {
        this.setData({ 'formData.remark': e.detail });
    },

    // 选择地址
    chooseAddress() {
        console.log('点击了服务地址'); // 调试用
        wx.navigateTo({
            url: '/pages/address/list',
            success: (res) => {
                console.log('跳转成功', res);
            },
            fail: (err) => {
                console.error('跳转失败', err);
            }
        });
    },

    // 表单验证
    validateForm() {
        const { categoryId, weight, timeSlotId } = this.data.formData;
        if (!categoryId) {
            wx.showToast({ title: '请选择回收品类', icon: 'none' });
            return false;
        }
        if (!weight || isNaN(weight) || weight <= 0) {
            wx.showToast({ title: '请输入有效的重量', icon: 'none' });
            return false;
        }
        if (!timeSlotId) {
            wx.showToast({ title: '请选择预约时间', icon: 'none' });
            return false;
        }
        if (!this.data.selectedDate) {
            wx.showToast({ title: '请选择预约日期', icon: 'none' });
            return false;
        }
        return true;
    },

    // 提交订单
    submitOrder() {
        if (!this.validateForm()) return;

        wx.showLoading({ title: '提交中...' });

        // 模拟提交订单
        setTimeout(() => {
            wx.hideLoading();
            wx.showToast({ title: '预约成功' });

            // 返回首页
            setTimeout(() => {
                wx.switchTab({ url: '/pages/home/home' });
            }, 1500);

        }, 1000);
    }
});